/**
 * @Title: PurchaseService.java
 * @Description: TODO(用一句话描述该文件做什么)
 * @author 张鑫
 * @phone 17561783855
 * @date 2019年4月8日
 */
package com.fortune.rainshineservice.service.impl;

import java.math.BigDecimal;
import java.util.*;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.plugins.Page;
import com.fortune.rainshinecommon.base.MsgModel;
import com.fortune.rainshinecommon.enums.ErrorCodes;
import com.fortune.rainshinecommon.enums.ResultCode;
import com.fortune.rainshinecommon.model.ProductModel;
import com.fortune.rainshinecommon.model.ShopModel;
import com.fortune.rainshinecommon.model.service.MessageModel;
import com.fortune.rainshinecommon.model.service.OrderDetailModel;
import com.fortune.rainshinecommon.model.service.OrderModel;
import com.fortune.rainshinecommon.model.service.StockModel;
import com.fortune.rainshinecommon.query.StockQuery;
import com.fortune.rainshineservice.mapper.OrderDetailMapper;
import com.fortune.rainshineservice.mapper.ProductMapper;
import com.fortune.rainshineservice.mapper.PurchaseMapper;
import com.fortune.rainshineservice.mapper.ShopMapper;
import com.fortune.rainshineservice.mapper.StockMapper;
import com.fortune.rainshineservice.service.MessageService;
import com.fortune.rainshineservice.service.PurchaseService;
import com.google.common.collect.Lists;

/**
 * @ClassName: PurchaseService
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author 张鑫
 * @phone 17561783855
 * @date 2019年4月8日
 *
 */
@Service
public class PurchaseServiceimpl implements PurchaseService {
    private static final Logger logger = LoggerFactory.getLogger(PurchaseServiceimpl.class);
    @Autowired
    private PurchaseMapper purchaseMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private ShopMapper shopMapper;
    
    @Autowired
    private MessageService messageService;

    @Override
    @Transactional
    public MsgModel order(OrderModel model) {
        try {
             if (model.getOrderList() == null || model.getOrderList().isEmpty()) {
                return new MsgModel("请选择产品！", ResultCode.FAILURE);
            }
            //生成订单id
             String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //根据shopid获取商铺信息
            ShopModel shop = shopMapper.selectById(model.getShopId());
            //为订单赋购买方商铺id
            model.setShopIdFrom(this.getShopUp(shop.getMerchantsId()).getId());

            BigDecimal totalPrice = new BigDecimal(0);
            int totalNum = 0;
            //处理订单详情
            for (OrderDetailModel item : model.getOrderList()) {
                 ProductModel product = productMapper.selectById(item.getProductId());
                //产品加个，根据角色判断使用哪个价格，招商价格和门店价格不同
                BigDecimal productPrice =model.getUser().getRoleId() == 5 ? product.getZsPrice() : product.getProductPrice();
                BigDecimal itemPrice = new BigDecimal(item.getQuantity()).multiply(productPrice);
                totalPrice = totalPrice.add(itemPrice);
                totalNum += item.getQuantity();
                item.setOrderCode(uuid);
                item.setProductPrice(productPrice);
                item.setTotalPrice(itemPrice);
                item.setCreateId(model.getUserId());
                orderDetailMapper.insert(item);
            }
            //处理订单
            model.setTotalNum(totalNum);
            model.setTotalPrice(totalPrice);
            model.setOrderCode(uuid);
            model.setOrderStatus((byte) 1);
            model.setCreateId(model.getUserId());
            model.setUpdateId(model.getUserId());
            purchaseMapper.insert(model);
            //像卖方插入采购信息
            ShopModel shopUp = this.getShopUp(shop.getMerchantsId());
            MessageModel message = new MessageModel(shopUp.getManagerId(),1,shop.getShopName());
            messageService.addMessage(message);
            
            return new MsgModel("下单成功！", ResultCode.SUCCESS);
        } catch (Exception e) {
            logger.error(ErrorCodes.BUSINESS_EXCEPTION.getMessage(), e);
            return new MsgModel("下单失败！", ResultCode.FAILURE);
        }
    }

    /**
     * @Title: getStockProducts
     * @Description: 获取上级店铺的库存信息
     * @author zhangxin
     * @phone 17561783855
     * @date 2019年5月6日
     */
    @Override
    public List<StockModel> getStockProducts(String shopId) {
        List<StockModel> stocks = new ArrayList<>();
        try {
            //根据shopid获取商铺
            ShopModel shop = shopMapper.selectById(shopId);

            //获取上级门店的商铺信息
            ShopModel shopUp = this.getShopUp(shop.getMerchantsId());

            //根据上级门店的shopId获取这个上级门店的库存信息
            Map<String, Object> columnMap = new HashMap<>();
            columnMap.put("shop_id", shopUp.getId());
            stocks = stockMapper.selectByMap(columnMap);

            //若库存不为空，则循环库存信息并查询出对应的产品信息返回
            if (!stocks.isEmpty()) {
                for (StockModel item : stocks) {
                    ProductModel product = productMapper.selectById(item.getProductId());
                    item.setProduct(product);
                }
            }
        } catch (Exception e) {
            logger.error(ErrorCodes.BUSINESS_EXCEPTION.getMessage(), e);
        }
        return stocks;
    }

    @Override
    public MsgModel getStockProductList(StockQuery query) {
        try {
            //根据shopid获取商铺
            ShopModel shop = shopMapper.selectById(query.getShopId());
            //获取上级门店的商铺信息
            ShopModel shopUp = this.getShopUp(shop.getMerchantsId());
            //根据上级门店的shopId获取这个上级门店的库存信息
//            Wrapper<StockModel> wrapper = new EntityWrapper<>();
//            wrapper.eq("shop_id", shopUp.getId());
//            wrapper.orderBy("create_time", false);
//            Page<StockModel> page = new Page<>(query.getPage(), query.getLimit());
//            List<StockModel> stocks = Optional.ofNullable(stockMapper.selectPage(page, wrapper)).orElse(Lists.newArrayList());
//            int total = stockMapper.selectCount(wrapper);
//            //若库存不为空，则循环库存信息并查询出对应的产品信息返回
//            if (!stocks.isEmpty()) {
//                for (StockModel item : stocks) {
//                    ProductModel product = productMapper.selectById(item.getProductId());
//                    item.setProduct(product);
//                }
//            }
            Page<StockModel> page = new Page<>(query.getPage(),query.getLimit());
            Map<String,Object> m = new HashMap<>();
            m.put("shopId",shopUp.getId());
            if(StringUtils.isNotBlank(query.getProductName())){
                m.put("productName",query.getProductName());
            }
            List<StockModel> stocks = Optional.ofNullable(stockMapper.getMerchantStocks(m, page)).orElse(Lists.newArrayList());
            if(!stocks.isEmpty()){
                for (StockModel item : stocks) {
                    ProductModel product = productMapper.selectById(item.getProductId());
                    item.setProduct(product);
                }
            }
            page.setRecords(stocks);
            return new MsgModel(page.getRecords().size(), page.getRecords());
        } catch (Exception e) {
            logger.error(ErrorCodes.BUSINESS_EXCEPTION.getMessage(), e);
            return new MsgModel("获取产品列表失败！", ResultCode.FAILURE);
        }
    }

    /**
     * @Title: getShopUp
     * @Description: 获取上级商铺信息
     * @author zhangxin
     * @phone 17561783855
     * @date 2019年5月9日
     */
    private ShopModel getShopUp(Integer managerId) {
        //获取上级门店的商铺信息
        ShopModel shop2 = new ShopModel();
        shop2.setManagerId(managerId);
        return shopMapper.selectOne(shop2);
    }

}
